package com.le.tester.javaThink.fourth.concurrency;


import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2021/11/4 16:08
 * description：运行的线程突然中断,IO和synchronized是无法进行中断的
 */

class SleepBlocked implements Runnable {

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println("Exiting sleepBlocked run()");
    }
}

//这个没有return，是永远不会释放锁的
class SynchronizedBlocked implements Runnable {
    public synchronized void f() {
        while (true) {
            //线程总是让出调度
            Thread.yield();
        }
    }

    public SynchronizedBlocked() {
        new Thread(this::f).start();
    }

    @Override
    public void run() {
        System.out.println("Trying to call f()");
        f();
        System.out.println("Exiting synchronizedBlocked.run()");
    }
}

class IOBlocked implements Runnable {
    private InputStream in;

    public IOBlocked(InputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        try {
            System.out.println("waiting for read():");
            int read = in.read();
            System.out.println("read is "+read);
        } catch (IOException e) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Interrupted from blocked I/O");
            } else {
                throw new RuntimeException(e);
            }
        }
        System.out.println("Exiting IOBlocked.run()");
    }
}

public class Interrupting {
    private static ExecutorService service = Executors.newCachedThreadPool();

    static void test(Runnable r) throws InterruptedException {
        //有返回值
        Future<?> f = service.submit(r);
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("Interrupting:" + r.getClass().getName());
        f.cancel(true);
        System.out.println("Interrupting sent to " + r.getClass().getName());
    }

    public static void main(String[] args) throws InterruptedException {
        test(new SleepBlocked());
        test(new IOBlocked(System.in));
        test(new SynchronizedBlocked());
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Aborting with System.exit(0)");
        System.exit(0);

    }

}
